package com.bw.ivideo

import android.app.Application
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.utils.LoggerUtils
import com.bw.lib_common.websocket.WebSocketUtils
import com.bw.lib_log.crash.CrashHandler
import com.tencent.mmkv.MMKV
import org.java_websocket.handshake.ServerHandshake


/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/13 19:36
 * @Description :
 */
class App: Application() {
    override fun onCreate() {
        super.onCreate()
        if(!ARouter.debuggable()){
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(this)//注意！！！init放在后面
        CrashHandler.getInstance().init(this)
        MMKV.initialize(this)
        //初始化webSocket
        WebSocketUtils.Builder()
//            .setWebsocket_url()
            .setListener(object : WebSocketUtils.ReceiveMsgListener {

                override fun onReceive(message: String) {
                    LoggerUtils.i("123",message)
                    showNotifacation(message)
                }

                override fun onOpen(handshakedata: ServerHandshake?) {
                    LoggerUtils.i("123","onOpen")
                }
                override fun onError(ex: Exception?) {
                    LoggerUtils.i("123","onError,${ex?.message}")
                }
                override fun onClose(code: Int, reason: String?, remote: Boolean) {}
            })
            .build()
    }

    //通知管理者
    private fun showNotifacation(message: String) {
        if (TextUtils.isEmpty(message)){
            return
        }

        //通知管理
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        var builder: Notification.Builder? = null
        //版本适配:安卓8.0后需要设置channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val channel =
                NotificationChannel("1", "通道1", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
            builder = Notification.Builder(this, "1")
        }else{
            builder = Notification.Builder(this)
        }

        //构建通知
        val intent = Intent(this, LiveActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val notification = builder.setContentTitle("消息")
            .setContentText(message)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)//点击跳转到直播页面
            .build()

        //发送通知
        notificationManager.notify(1, notification)
    }
}